package com.asset.modules.system.controller;

import com.asset.modules.assets.service.AssetService;
import com.asset.modules.budget.model.Budget;
import com.asset.modules.budget.service.BudgetService;
import com.asset.modules.common.model.ParamBean;
import com.asset.modules.common.model.ResponseBean;
import com.asset.modules.common.utils.StringUtil;
import com.asset.modules.system.model.Company;
import com.asset.modules.system.model.Project;
import com.asset.modules.system.service.CompanyService;
import com.asset.modules.system.service.impl.ProjectServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenchen
 */
@RestController
@CrossOrigin
@RequestMapping("/project")
@Api(tags = "项目公司信息接口")
public class ProjectController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProjectController.class);

    private static final String SUPER_CODE = "-1";
    @Autowired
    ProjectServiceImpl projectService;

    @Autowired
    CompanyService companyService;

    @Autowired
    AssetService as;

    @Autowired
    BudgetService bs;

    @ApiOperation(value = "项目公司信息的保存和更新")
    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean saveOrModify(@RequestBody Project project){
        try {
            projectService.saveOrUpdate(project);
            return new ResponseBean(HttpStatus.OK.value(), "项目公司信息保存或更新成功!",true);
        }catch (Exception e){
            LOGGER.error(e.getMessage());
            return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "信息保存失败，请查看编码和名称是否重复!",false);
        }

    }

    @ApiOperation(value = "根据ID获取项目公司信息")
    @RequestMapping(value = "/byId", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBean getProjectById(@RequestParam String id){
        Project p = projectService.getById(id);
        Company c = companyService.getById(p.getCompanyId());
        p.setCompanyCode(c.getCompanyCode());
        p.setCompanyName(c.getCompanyName());
        return new ResponseBean(HttpStatus.OK.value(), "获取公司信息成功!", p);
    }


    @ApiOperation(value = "删除项目公司信息")
    @RequestMapping(value = "/removeProject", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBean removeProject(@RequestParam String ids){
        boolean flag = true;
        String msg = "删除信息";
        if(StringUtil.isBlank(ids)){
            flag = false;
            msg  = "待删除项目ID为空";
            return new ResponseBean(HttpStatus.OK.value(), msg, flag);
        }
        String[] removeIds = ids.split(",");
        List list = new ArrayList();
        for(String id : removeIds){
            flag = as.isExist("project_id", id);
            if(flag){
               return new ResponseBean(401, "待删除项目公司有关联固资数据，请先删除关联固资数据!", id);
            }
            flag = bs.isExist("project_id", id);
            if(flag){
               return new ResponseBean(401, "待删除项目公司有关联预算数据，请先删除关联预算数据!", id);
            }
            list.add(id);
        }
        flag = projectService.removeByIds(list);
        return new ResponseBean(HttpStatus.OK.value(), msg, flag);
    }



    @ApiOperation(value="根据区域ID获取项目公司列表分页")
    @RequestMapping(value = "/getProjectsPageByCompanyId", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean getProjectsByCompanyCode(@RequestBody Page page, @RequestParam String id){
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        Company c = companyService.getById(id);
        String code = c.getCompanyCode();
        if(!code.equals(SUPER_CODE)){
            queryWrapper.eq("company_id", c.getId());
        }else{
            queryWrapper.isNotNull("company_id");
        }
        IPage<Project> projects = projectService.page(page, queryWrapper);
        List<Project> result = new ArrayList<>();
        List<Project> ps = projects.getRecords();
        for(Project p : ps){
            p.setCompanyCode(c.getCompanyCode());
            p.setCompanyName(c.getCompanyName());
            result.add(p);
        }
        projects.setRecords(result);
        return new ResponseBean(HttpStatus.OK.value(), "获取项目信息成功！", projects);
    };

    @ApiOperation(value = "根据区域ID获取项目公司列表，有预算的项目公司往前排")
    @RequestMapping(value = "/getProjectsByCompanyId", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBean getProjectsByCompanyCode(@RequestParam String id){
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", id);
        Company c = companyService.getById(id);
        List<Project> projects = projectService.list(queryWrapper);
        List<Project> result   = new ArrayList<>();
        List<Project> noBudgetList = new ArrayList<>();
        //将项目公司分为有预算集，与无预算集
        for(Project p : projects){
            List<Budget> budgets = bs.getBudgetByProjectId(p.getId().toString());
            p.setCompanyCode(c.getCompanyCode());
            p.setCompanyName(c.getCompanyName());
            if(budgets.size()>0){
                result.add(p);
            }else{
                noBudgetList.add(p);
            }
        }
        result.addAll(noBudgetList);
        return new ResponseBean(HttpStatus.OK.value(), "请求成功！", result);
    }

    @ApiOperation(value = "检查项目名称是否存在")
    @RequestMapping(value = "/isExist", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean isExist(@RequestBody ParamBean param){
        return new ResponseBean(HttpStatus.OK.value(), "请求成功", projectService.isExist(param.getColumn(), param.getValue()));
    }
}
